<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>访问器保护数据</title>
  <!-- https://www.w3school.com.cn/js/js_object_accessors.asp -->
</head>

<body>

</body>
<script>
  "use strict"; {
    const web = {
      name: "好人",
      url: "baidu",
      set site(value) {
        return [this.url, this.name] = value.split(":");
      },
      get site() {
        return `${this.name}的网站是${this.url}.com`;
      }
    }
    web.site = "开源网站了:houdunren.com";
    console.log(JSON.stringify(web, null, 4));
  }; {
    // 案列: 使用访问器存储token值
    let request = {
      set token(content) {
        localStorage.setItem("token", content);
      },
      get token() {
        let token = localStorage.getItem("token");
        if (!token) alert(`请登录`);
        return token;
      }
    }
    request.token = ``;
    console.log(request.token);
  };
</script>

</html>